// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const $ = db.command.aggregate

const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const {
    currentMonth: curr,
    lastMonth,
    nickname
  } = event
  // console.log("add----------");
  const {
    list
  } = await db.collection('order-list')
    .aggregate()
    .addFields({
      formatDate: $.dateToString({
        date: '$createTime',
        format: '%Y-%m',

      })
    })
    .match({
      formatDate: _.eq(curr),
      nickname: _.eq(nickname),
      orderStatus:_.eq(2)
    })
    .project({
      _id: 0,
      amount: 1,
      price: 2,
      priceCommission: 3,
      formatDate: $.dateToString({
        date: '$createTime',
        format: '%Y-%m',

      })

    })
    .end()

  const {
    list: list1
  } = await db.collection('order-list')
    .aggregate()
    .addFields({
      formatDate: $.dateToString({
        date: '$createTime',
        format: '%Y-%m',

      })
    })
    .match({
      formatDate: _.eq(lastMonth),
      nickname: _.eq(nickname),
      orderStatus: _.eq(2)
    })
    .project({
      _id: 0,
      price: 1,
      formatDate: $.dateToString({
        date: '$createTime',
        format: '%Y-%m',

      })

    })
    .end()
  // console.log('list111111111111111',list1);
  const last = list1.map(e => parseFloat(e.price || 0)).reduce((x, y) => (x + y),0).toFixed(2)

  const month = list.map(e => parseFloat(e.price || 0)).reduce((x, y) => (x + y),0).toFixed(2)
  const commission = list.map(e => {
      const priceCommission = parseFloat(e.priceCommission) / 100
      const mytc = (1 - priceCommission) * e.price
      return mytc
    })
    .reduce((x, y) => x + y,0)
    .toFixed(2)

  return {
    month,
    commission,
    last
  }
}